﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;

namespace WcfFlashRemoting.ServiceModel.Channels
{
    abstract class AmfBaseMessage : Message
    {
        MessageHeaders headers;
        MessageProperties properties;
        AmfObjects.AmfHeader[] amfHeaders;
        MessageVersion version;


        public AmfBaseMessage(MessageVersion messageVersion, AmfObjects.AmfHeader[] amfHeaders, ushort amfVersion)
        {
            this.amfHeaders = amfHeaders;
            this.version = messageVersion;

            headers = new MessageHeaders(version);
            headers.Action = null;
            headers.FaultTo = null;
            headers.From = null;
            headers.To = null;

            properties = new MessageProperties();
            properties.AllowOutputBatching = true;
            properties.Via = null;

            AmfVersion = amfVersion;
        }

        public AmfObjects.AmfHeader[] AmfHeaders { get { return amfHeaders; } }

        public override MessageHeaders Headers
        {
            get { return headers; }
        }

        protected override void OnWriteBodyContents(System.Xml.XmlDictionaryWriter writer)
        {
        }

        public override MessageProperties Properties
        {
            get { return properties; }
        }

        public override MessageVersion Version
        {
            get { return version; }
        }

        public ushort AmfVersion
        {
            get
            {
                return (ushort)properties["amfVersion"];
            }
            set
            {
                if (!AmfVersions.VerifyAmfVersion(value))
                {
                    throw new ArgumentException();
                }

                if (properties.ContainsKey("amfVersion"))
                {
                    properties["amfVersion"] = value;
                }
                else
                {
                    properties.Add("amfVersion", value);
                }
            }
        }

        public static ushort GetCurrentAmfVersion
        {
            get
            {
                if (System.ServiceModel.OperationContext.Current == null)
                {
                    return AmfVersions.HighestVersion;
                }
                return (ushort)(System.ServiceModel.OperationContext.Current.IncomingMessageProperties["amfVersion"]);
            }
        }
    }
}
